package com.edu.dreams.controller;

import com.edu.dreams.entity.User;
import com.edu.dreams.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

//@Controller注解
@Controller

public class UserController {

	@Autowired
	UserMapper userMapper;

	@PostMapping("userlogin")
	@ResponseBody
	public String userlogin(String username, String password, HttpServletRequest request) {
		User user = userMapper.userlogin(username, password);
		if (user != null) {
			request.getSession().setAttribute("user", user);
			if ("1".equals(user.getUser_role())) {
				return "<script>window.location.href='adminhome';</script>";
			} else {
				return "<script>window.location.href='home';</script>";
			}
		}
		return "<script>alert('用户名或密码错误！');window.location.href='login';</script>";
	}

	@PostMapping("userReg")
	@ResponseBody
	public String userReg(String username, String password, HttpServletRequest request) {
		int res = 0;
		try {
			res = userMapper.userregister(username, password);
		} catch (Exception e) {
			e.printStackTrace();
			return "<script>alert('注册失败!');window.location.href='login';</script>";
		}
		return "<script>alert('" + ((res == 1) ? "注册成功！" : "注册失败！") + "');window.location.href='login';</script>";
	}

	@PostMapping("updatepersonal")
	@ResponseBody
	public String update_personal(User user) {
		int res = userMapper.updateUser(user);
		return "<script>alert('" + ((res == 1) ? "更新成功！" : "更新失败！") + "');window.location.href='personal';</script>";
	}
}
